#include "pthread.h"
#include "stdint.h"
#include "time.h"

#include "datapool_mutex.h"
#include "Dual_Link_List.h"

void* data_process_thread(void* arg)
{
	printf("&data_process_thread: data process thread started.\n");

	int8_t set_message_ret_val;
	p_ListNode p_node = NULL;
	int lock_ret_val, unlock_ret_val;

	lock_ret_val = pthread_mutex_lock(&mutex_list);
	if(0 != lock_ret_val) {
		printf("&data_process_thread: Fail to lock mutex of data pool,"
				" data process thread exit.\n");
		pthread_exit(NULL);
	}

	p_node = p_list;
	p_node = get_next_node(p_node);

	while(1) {
		if( (p_list != p_node) && (NULL == get_additional_message(p_node)) ) {
			set_message_ret_val = set_additional_message_for_node(p_node, (void*)"processed");
			if(-1 == set_message_ret_val) {
				printf("&data_process_thread: Fail to set additional message for data pool node,"
						"data process thread exit.\n");
				pthread_exit(NULL);
			}
#ifdef DEBUG
			printf("&data_process_thread: the additional message has been set.\n");
#endif
			unlock_ret_val = pthread_mutex_unlock(&mutex_list);
			if(0 != unlock_ret_val) {
				printf("&data_process_thread: fail to unlock mutex of data pool, "
						"data process thread exit.\n");
				pthread_exit(NULL);
			}
		}
		else if(p_list == p_node){
			printf("&data_process_thread: The data pool is empty, wait for 5 seconds.\n");
			unlock_ret_val = pthread_mutex_unlock(&mutex_list);
			if(0 != unlock_ret_val) {
				printf("&data_process_thread: fail to unlock mutex of data pool, "
						"data process thread exit.\n");
				pthread_exit(NULL);
			}
			sleep(5);
		}
		else {
			unlock_ret_val = pthread_mutex_unlock(&mutex_list);
			if(0 != unlock_ret_val) {
				printf("&data_process_thread: fail to unlock mutex of data pool, "
						"data process thread exit.\n");
				pthread_exit(NULL);
			}
		}

		lock_ret_val = pthread_mutex_lock(&mutex_list);
		if(0 != lock_ret_val) {
			printf("&data_process_thread: Fail to lock mutex of data pool,"
					" data process thread exit.\n");
			pthread_exit(NULL);
		}

		p_node = get_next_node(p_node);
	}

	printf("&data_process_thread: data process thread exit.\n");
	return NULL;
}
